<template>
  <div class="liteflow-editor-outline">
    <a-tree
      v-if="treeData.length"
      :tree-data="treeData"
      :defaultExpandAll="true"
    >
      <template slot="title" slot-scope="{ dataRef }">
        <img
          v-if="dataRef.icon"
          :src="dataRef.icon"
          style="width: 16px; height: 16px; margin-right: 8px; vertical-align: middle;"
        />
        <span>{{ dataRef.title }}</span>
      </template>
    </a-tree>
    <div v-else class="empty">暂无数据</div>
  </div>
</template>

<script>
import { getModel } from '../../core/state/model.js';
import { PALETTE_GROUPS } from '../../core/palette/groups.js';

export default {
  name: 'Outline',
  inject: ['flowGraph'],
  data() {
    return {
      treeData: [],
    };
  },
  created() {
    this.updateTree();
  },
  mounted() {
    const graph = this.flowGraph?.value || this.flowGraph;
    if (graph) {
      graph.on('model:changed', this.updateTree);
    }
  },
  activated() {
    this.updateTree();
  },
  beforeDestroy() {
    const graph = this.flowGraph?.value || this.flowGraph;
    if (graph) {
      graph.off('model:changed', this.updateTree);
    }
  },
  methods: {
    transformer(model) {
      const { id, type } = model;
      const title = id ? `${id} : ${type}` : type;
      const key = `${type}-${id || ''}-${Math.random()}`;
      
      // 获取组件图标
      const icon = this.getIconByType(type);
      
      const node = {
        key,
        title,
        icon,
        children: [],
        scopedSlots: { title: 'title' },  // 使用自定义 title slot
      };
      
      if (model.condition) {
        node.children.push(this.transformer(model.condition));
      }
      
      if (model.children && model.children.length) {
        model.children.forEach(child => {
          if (child) {
            node.children.push(this.transformer(child));
          }
        });
      }
      
      if (node.children.length === 0) {
        delete node.children;
      }
      
      return node;
    },
    getIconByType(type) {
      // 从 PALETTE_GROUPS 中查找对应的图标
      for (const group of PALETTE_GROUPS) {
        const cell = group.cellTypes.find(c => c.type === type);
        if (cell && cell.icon) {
          return cell.icon;
        }
      }
      return null;
    },
    updateTree() {
      const model = getModel();
      if (model) {
        this.treeData = [this.transformer(model)];
      } else {
        this.treeData = [];
      }
    },
  },
};
</script>

<style lang="less">
.liteflow-editor-outline {
  padding: 16px;
  height: 100%;
  overflow: auto;
  
  .empty {
    color: #999;
    text-align: center;
    padding: 20px;
  }
  
  .ant-tree {
    color: #000;
    font-size: 14px;
  }
}
</style>
